package org.bocs.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.bocs.config.BusinessException;
import org.bocs.untils.JwtHelper;
import org.bocs.untils.ResultVo;
import org.bocs.untils.StateCode;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class InterceptorValidToken implements HandlerInterceptor {
    // 创建拦截器拦截请求token
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        // 校验token
        if(token == null) {
            ResultVo resultVo = new ResultVo(StateCode.FAIL, "请先登录！", null);
            doResponse(response, resultVo);
            return false;
        } else {
            try {
                JwtHelper.tokenExpired(token);
                return true;
            } catch (ExpiredJwtException e){
                ResultVo resultVo = new ResultVo(StateCode.FAIL, "登录过期，请重新登录！", null);
                doResponse(response, resultVo);
            } catch (UnsupportedJwtException e){
                ResultVo resultVo = new ResultVo(StateCode.FAIL, "Token不合法！", null);
                doResponse(response, resultVo);
            } catch (Exception e){
                ResultVo resultVo = new ResultVo(StateCode.FAIL, "登录过期，请重新登录！", null);
                doResponse(response, resultVo);
            }
        }
        return false;
    }

    private void doResponse(HttpServletResponse response, ResultVo resultVo) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(resultVo);
        writer.print(s);
        writer.flush();
        writer.close();
    }

}
